import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { IThunkState } from '@/global/type'
import { localCache } from '@/utils/cache'
import { message } from 'antd'

interface IWebsocketState {
  unsentMessageInfo: string[]
  // websocketInstance: WebSocket | null
  messageList: string[]
}

/* 数据区 */
const WEBSOCKET_URL = 'ws://www.cyljx.xyz:8089/wsServer/'
const initialState: IWebsocketState = {
  // 用于存储因网络异常等操作未发生信息存储
  unsentMessageInfo: [],
  // websocket实例
  // websocketInstance: null,
  // 聊天记录列表
  messageList: []
}

/** 异步action **/
// 初始化websocket
export const initWebsocketAction = createAsyncThunk<void, any, IThunkState>(
  'init/websocket',
  async (_, { getState, dispatch }) => {
    const userId = getState().app.userInfo.userId
    const websocketInstance = new WebSocket(WEBSOCKET_URL + userId)
    console.log(websocketInstance)
    dispatch(handleMessageAction(websocketInstance))
    dispatch(handleErrorAction(websocketInstance))
    dispatch(handleCloseAction(websocketInstance))
  }
)

export const handleMessageAction = createAsyncThunk(
  'handleMessage',
  (websocketInstance: WebSocket) => {
    websocketInstance.onmessage = function (e) {
      console.log(JSON.parse(e.data))
      // 服务器返回的消息实体
      const messageEntity = JSON.parse(e.data)
      // 判断是否为系统管理员操作的消息记录
      if (messageEntity.admin === true) {
        let content = ''
        localCache.clear()
        switch (messageEntity.content) {
          case 'delete':
            content =
              '由于您的账号进行了违规操作，账号已被管理员删除，如有疑问请联系客服进行处理~'
            console.log(content)
            break
          case 'banned':
            content = '您已经被封号，请重新登录~'
            console.log(content)
            break
          case 'resetPassword ':
            content = '您的密码已被重置，请重新登录~'
            console.log(content)
            break
          case 'kickOut':
            content = '您已被强制下线~'
            console.log(content)
            break
          case 'assignRole':
            content = '您的角色已经更新,请重新登录~'
            console.log(content)
            break
          case 'roleUpdateMenu ':
            content = '您的角色权限已经更新,请重新登录~'
            console.log(content)
            break
        }
        message.info(content)
        window.location.hash = '/login'
      }
    }
  }
)

// 处理异常信息消息
export const handleErrorAction = createAsyncThunk(
  'handleError',
  (websocketInstance: WebSocket) => {
    websocketInstance.onerror = function (e) {
      // console.log(e)
    }
  }
)
// 处理关闭信息
export const handleCloseAction = createAsyncThunk(
  'handleClose',
  (websocketInstance: WebSocket) => {
    websocketInstance.onclose = function (e) {
      // console.log(e)
    }
  }
)
// 主动退出
export const handleInitiativeCloseAction = createAsyncThunk(
  'handleInitiativeClose',
  (websocketInstance: WebSocket) => {
    websocketInstance.close()
  }
)

const websocketSlice = createSlice({
  name: 'websocket',
  initialState,
  reducers: {}
})

// export const {} = websocketSlice.actions
export default websocketSlice.reducer
